(function(){
  function initBottomNavActive() {
    const nav = document.getElementById('global-bottom-nav');
    if (!nav) return;
    const items = nav.querySelectorAll('.bottom-nav-item, .bottom-nav-sell-btn');

    // 根据当前路径高亮
    const path = location.pathname.split('/').pop() || 'index.html';
    const map = {
      'index.html': 'home',
      'local.html': 'city',
      'message.html': 'message',
      'center.html': 'my'
    };
    const current = map[path];
    items.forEach(el=>el.classList.remove('active'));
    if (current) {
      const active = nav.querySelector(`[data-tab="${current}"]`);
      if (active) active.classList.add('active');
    }

    // 切换时更新图标
    const iconMap = {
      'home': {
        active: 'image/bottom_nav/ic_tabbar_home_sel.png',
        inactive: 'image/bottom_nav/ic_tabbar_home_nor.png'
      },
      'city': {
        active: 'image/bottom_nav/ic_tabbar_city_sel.png',
        inactive: 'image/bottom_nav/ic_tabbar_city_nor.png'
      },
      'message': {
        active: 'image/bottom_nav/ic_tabbar_message_sel.png',
        inactive: 'image/bottom_nav/ic_tabbar_message_nor.png'
      },
      'my': {
        active: 'image/bottom_nav/ic_tabbar_my_sel.png',
        inactive: 'image/bottom_nav/ic_tabbar_my_nor.png'
      }
    };

    function refreshIcons(activeTab){
      items.forEach(item=>{
        const tab = item.getAttribute('data-tab');
        const img = item.querySelector('.bottom-nav-icon');
        if (!tab || !img || !iconMap[tab]) return;
        img.src = (tab === activeTab) ? iconMap[tab].active : iconMap[tab].inactive;
      });
    }
    refreshIcons(current);

    items.forEach(item=>{
      item.addEventListener('click', function(e){
        const href = this.getAttribute('href');
        if (href && href !== '#') return; // 跳转页保持默认
        e.preventDefault();
        items.forEach(x=>x.classList.remove('active'));
        this.classList.add('active');
        const tab = this.getAttribute('data-tab');
        refreshIcons(tab);
      });
    });
  }

  // 暴露全局，以便在各页面动态注入后调用
  window.initBottomNav = initBottomNavActive;
})();